/*
 * @Autor: dingxiaolin
 * @Date: 2020-04-14 13:30:31
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-05-02 17:39:59
 */
const getRawBody = require('raw-body');
const request = require('request-promise')
const key = process.env['AmapKey']
const search = async (query) => {
    query.key = key;
    var options = {
        uri: 'https://restapi.amap.com/v3/config/district',
        qs: query,
        json: true
    };
    const result = await request(options)
    return result
}

// 入口函数
module.exports.handler = function (req, resp, context) {
    getRawBody(req, async (err, body) => {
        try {
            console.log('req.queries', req.queries)
            const data = await search(req.queries)
            if (data.status == "1") {//amap请求成功
                if (data.districts.length > 0) {//amap请求有结果
                    sendResp(data, true)
                } else {
                    sendResp("未查询到信息", false)
                }
            } else {   //amap请求失败，如key错误
                sendResp(data, false)
            }
        } catch (err) {
            console.log('err', err)
        }
    });

    // 返回
    sendResp = (data, boolean) => {
        resp.setHeader('content-type', 'application/json');
        try {
            resp.send(JSON.stringify({
                success: boolean,
                data: data
            }));
        }
        catch (err) {
            resp.send(JSON.stringify({
                success: false,
                data: err.message
            }));
        }
    }

}